<template>
  <a-layout :style="{width: '100%'}">
    <top-bar @shopcarItems="getShopCarItems"/>
    <a-layout-content :style="{padding: '0 50px', marginTop: '64px', minHeight: '620px'}">
      <a-table style="margin-top: 18px" :row-selection="rowSelection" :columns="columns" :data-source="data" :pagination="{ pageSize: 10 }"
               :scroll="{ y: 450 }">
        <template #headerCell="{ column }">
          <template v-if="column.key === 'skuName'">
            <span>
              <smile-outlined />
              商品
            </span>
          </template>
          <template v-if="column.key === 'price'">
            <span>
              <money-collect-outlined />
              单价
            </span>
          </template>
        </template>

        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'skuDefaultImg'">
            <a-image
                :width="100"
                :src=record.skuDefaultImg
            />
            <a-tag v-if="record.hasStock===false" color="warning">
              <template #icon>
                <exclamation-circle-outlined />
              </template>无货</a-tag>
          </template>
          <template v-if="column.key === 'skuName'">
            <router-link :to="{path: '/product/info/baseAttrs', query: {skuId: record.skuId}}">
              {{ record.skuName }}
            </router-link>
          </template>
          <template v-if="column.key === 'saleAttrs'">
            <a-tag color="cyan" v-for="attr in record.saleAttrs">{{attr}}</a-tag>
          </template>
          <template v-if="column.key === 'price'">
            <span>
              ￥{{record.price}}
            </span>
          </template>
          <template v-if="column.key === 'count'">
            <a-input-number id="inputNumber" v-model:value="record.count" :min="1" @change="countChange(record.skuId, record.count)">
              <template #upIcon>
                <ArrowUpOutlined />
              </template>
              <template #downIcon>
                <ArrowDownOutlined />
              </template>
            </a-input-number>
          </template>
          <template v-if="column.key === 'totalPrice'">
            <div style="align-items: center; justify-content: center">
              <span>
                <a-typography-title :level="5">
                  <pay-circle-outlined :style="{fontSize: '18px'}"/>
                  {{record.totalPrice}}
                </a-typography-title>
            </span>
            </div>
          </template>
          <template v-if="column.key === 'operation'">
            <a>
              <delete-outlined :style="{fontSize: '20px'}" @click="delItem(record.skuId)"/>
            </a>
          </template>
        </template>
        <template #footer>
          <a-row>
            <a-col :span=4>
              <a-button type="dashed" danger :disabled="!hasSelected" :loading="state.loading" @click="delSelected">
                合并删除
              </a-button>
            </a-col>
            <a-col :span="16"><!--TODO 占位--></a-col>
            <a-col :span="4">
              <a-typography-title :level="4" style="color: red">
                总价：{{sumPrice}} ￥
              </a-typography-title>
              <a-button :disabled="!submitOrderVisible" @click="gotoOrderInfo">结算</a-button>
            </a-col>
          </a-row>
        </template>
      </a-table>
    </a-layout-content>
    <tail-bar/>
  </a-layout>
</template>

<script setup>
import TopBar from "@/components/common/TopBar.vue";
import TailBar from "@/components/common/TailBar.vue";
import {computed, ref, unref, reactive, createVNode, onBeforeMount} from 'vue';
import {message, Table} from 'ant-design-vue';
import { SmileOutlined, MoneyCollectOutlined, ArrowUpOutlined, ArrowDownOutlined, DeleteOutlined, ExclamationCircleOutlined, PayCircleOutlined} from '@ant-design/icons-vue';
import request from "@/utils/request";
import { Modal } from 'ant-design-vue';
import {publish} from "pubsub-js";
import router from "@/router";

let data = ref([]); //购物车数据源
let skuIndexMap = new Map()  //{key: skuId, value: data的index}

const getShopCarItems = (data_temp) => {
  data.value = []
  let skuIds = []
  for (let i = 0; i < data_temp.length; i++) {
    let temp = data_temp[i]
    temp['key'] = data_temp[i].skuId
    data.value.push(temp)
    skuIndexMap.set(data_temp[i].skuId, i)
    skuIds.push(data_temp[i].skuId)
  }
}

/**
 *
 * @param skuId
 * @param st 批量删除状态。如果有这个参数，就把按钮回制
 * @returns {Promise<unknown | void>}
 */
const delItem = (skuId, st) => {
  let data = []
  if(Array.isArray(skuId)){
    skuId.forEach(item => {
      data.push(item)
    })
  } else {
    data.push(skuId)
  }
  Modal.confirm({
    title: '你忍心去掉购物车里的商品吗？ 好好想想！',
    icon: createVNode(ExclamationCircleOutlined),
    content: '后续可能会更便宜哦，请关注~~~',
    onOk() {
      return new Promise((resolve, reject) => {
        request({
          url: '/auth/user/shop-car/delItem',
          method: 'post',
          data: request.adornData(data, false)
        }).then(res => {
          if(res.code === 0){
            message.success(res.msg)
            resolve(res)
          } else {
            message.info(`[${res.code}]-`+res.msg)
            reject(res)
          }
          //更新购物车
          publish("delItem", "购物车删除了一个商品")
          //批量删除的情况
          if(typeof st !== "undefined"){
            state.loading = false;
            state.selectedRowKeys = [];
          }
        })
      }).catch((err) => console.log('Oops errors!', err.message));
    },
    // eslint-disable-next-line @typescript-eslint/no-empty-function
    onCancel() {
      state.loading = false
    },
  });
}

const hasSelected = computed(() => state.selectedRowKeys.length > 0);
const submitOrderVisible = computed(() => selectedRowKeys.value.length > 0)

//被勾选的集合
const state = reactive({
  selectedRowKeys: [],
  // Check here to configure the default column
  loading: false,
});

//要显示的总价
let sumPrice = ref(0)

//合并删除
const delSelected = () => {
  state.loading = true;
  // ajax request after empty completing
  delItem(state.selectedRowKeys, 'state')
};

const columns = [
  {
    title: 'logo',
    dataIndex: 'skuDefaultImg',
    key: 'skuDefaultImg'
  },
  {
    title: '商品',
    dataIndex: 'skuName',
    key: 'skuName'
  },
  {
    title: '规格',
    dataIndex: 'saleAttrs',
    key: 'saleAttrs'
  },
  {
    title: '单价',
    dataIndex: 'price',
    key: 'price'
  },
  {
    title: '数量',
    dataIndex: 'count',
    key: 'count'
  },
  {
    title: '小计',
    dataIndex: 'totalPrice',
    key: 'totalPrice'
  },
  {
    title: '操作',
    dataIndex: 'operation',
    key: 'operation'
  },
];


const selectedRowKeys = ref([]); // 搜集选中的skuId

function countChange(skuId, count){
  let index = skuIndexMap.get(skuId)
  data.value[index].totalPrice = data.value[index].price*count
  request({
    url: '/auth/user/shop-car/addItem',
    method: 'post',
    params: {skuId, count}
  }).then(res => {
    console.log(res)
  }).catch(err => {
    console.log(err.message)
  })
}


const onSelectChange = changableRowKeys => {
  selectedRowKeys.value = changableRowKeys;
  console.log('选中的行', changableRowKeys)
  state.selectedRowKeys = selectedRowKeys;
  sumPrice.value = 0
  changableRowKeys.forEach(skuId => {
    sumPrice.value += data.value[skuIndexMap.get(skuId)].totalPrice
  })
};


const gotoOrderInfo = ()=>{
  let collectSkuIds = ''
  let len = selectedRowKeys.value.length
  for (let i = 0; i < len; i++) {
    let skuId = selectedRowKeys.value[i]
    collectSkuIds += (`${skuId}:${data.value[skuIndexMap.get(skuId)].count}`)
    if(i < len-1){
      collectSkuIds+=','
    }
  }
  router.push({
    name: "orderInfo",
    params: {skuIds: collectSkuIds, status: 'preSubmit'}
  })
}


// 设置没有库存的商品无法勾选
const getCheckbox = (record)=>{
  return{
    disabled: record.hasStock === false,
  }
}

const rowSelection = computed(() => {
  return {
    selectedRowKeys: unref(selectedRowKeys),
    onChange: onSelectChange,
    hideDefaultSelections: true,
    getCheckboxProps: getCheckbox,
    selections: [
      Table.SELECTION_ALL,
      Table.SELECTION_INVERT,
      Table.SELECTION_NONE,
      {
        key: 'odd',
        text: 'Select Odd Row',
        onSelect: changableRowKeys => {
          let newSelectedRowKeys = [];
          newSelectedRowKeys = changableRowKeys.filter((_key, index) => {
            if (index % 2 !== 0) {
              return false;
            }
            return true;
          });
          selectedRowKeys.value = newSelectedRowKeys;
        },
      },
      {
        key: 'even',
        text: 'Select Even Row',
        onSelect: changableRowKeys => {
          let newSelectedRowKeys = [];
          newSelectedRowKeys = changableRowKeys.filter((_key, index) => {
            if (index % 2 !== 0) {
              return true;
            }
            return false;
          });
          selectedRowKeys.value = newSelectedRowKeys;
        },
      },
    ],
  };
});

</script>
